/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kz.shange.daosMongo;

import java.util.Date;
import java.util.List;
import org.kz.shange.common.KzResp;
import org.kz.shange.models.Author;
import org.kz.shange.models.Fun;
import org.kz.shange.models.FunMeta;
import org.kz.shange.models.IWosahDao;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.data.mongodb.core.query.Query;

/**
 *
 * @author Administrator
 */
public class WosahDaoImpl implements IWosahDao {

    private MongoOperations daoTemplate;

    @Override
    public KzResp<Fun> saveFun(FunMeta f) {
        KzResp<Fun> kr = new KzResp<>();
        try {
            Author aut = daoTemplate.findById(f.getAuthorId(), Author.class);
            Fun fun = new Fun(aut, f.getText(), f.getResLink(), new Date());
            this.daoTemplate.save(fun);
            kr.success(fun);
        } catch (Exception ex) {
            kr.error(ex.getMessage());
        }
        return kr;
    }

    @Override
    public KzResp<List<Fun>> loadReaderInterestFuns(String uid, int from, int size) {
        KzResp<List<Fun>> kr = new KzResp<>();
        try {
            Sort s = new Sort(new Sort.Order(Sort.Direction.DESC, "atTime"));
            Query q = new Query().with(s).skip(from).limit(size);
            if (!uid.equals("-1")) {
                q.addCriteria(where("author").is(uid));
            }
            List<Fun> fs = this.daoTemplate.find(q, Fun.class);
            kr.success(fs);
        } catch (Exception ex) {
            kr.error(ex.getMessage());
        }
        return kr;
    }

//<editor-fold defaultstate="collapsed" desc="property">
    public MongoOperations getDaoTemplate() {
        return daoTemplate;
    }

    public void setDaoTemplate(MongoOperations daoTemplate) {
        this.daoTemplate = daoTemplate;
    }
//</editor-fold>

}
